package cn.wj.school.server.net.context;

import cn.wj.school.app.dto.UserDTO;
import cn.wj.school.cloud.dto.SyUserDTO;
import cn.wj.school.cloud.enums.UserType;
import cn.wj.school.common.dto.BaseMsg;
import cn.wj.school.server.net.utils.ChannelUtils;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public enum SessionManager {

    INSTANCE;

    private Logger logger = LoggerFactory.getLogger(SessionManager.class);

    /**
     * 缓存通信上下文环境对应的登录用户（主要用于服务）
     */
    private Map<IoSession, Long> session2userIds = new ConcurrentHashMap<>();

    /**
     * 缓存用户id与对应的会话
     */
    private Map<Long, IoSession> userId2Sessions = new ConcurrentHashMap<>();

    /**
     * 缓存老师id与对应的会话
     */
    private Map<Long, IoSession> teacherSession = new ConcurrentHashMap<>();


    /**
     * 向单一在线用户发送数据包
     */
    public void sendMsgTo(IoSession session, BaseMsg pact) {
        if (pact == null || session == null) {
            return;
        }
        session.sendMsg(pact);
    }

    public void sendMsgTo(UserDTO user, BaseMsg pact) {
        IoSession session = userId2Sessions.get(user.getId());
        if (session != null) {
            session.sendMsg(pact);
        }
    }

    public void sendMsgTo(Long userId, BaseMsg pact) {
        if (pact == null || userId <= 0) {
            return;
        }

        IoSession session = userId2Sessions.get(userId);
        if (session != null) {
            session.sendMsg(pact);
        }
    }

    public void sendMsgTo(Channel channel, BaseMsg pact) {
        if (pact == null || channel == null) {
            return;
        }
        channel.writeAndFlush(pact);
    }

    /**
     * 向所有在线用户发送数据包
     */
    public void notifyToAllOnlineUserDTOs(BaseMsg pact) {
        if (pact == null) {
            return;
        }

        userId2Sessions.values().forEach(session -> session.sendMsg(pact));
    }

    public IoSession getSessionBy(long userId) {
        return this.userId2Sessions.get(userId);
    }

    /**
     * 判断是否有值
     * 已存在返回true
     * @return
     */
    public Boolean hasTeacher() {
        return !this.teacherSession.isEmpty();

    }

    public boolean registerSession(SyUserDTO user, IoSession session) {
        //说明
       /* IoSession oldSession = userId2Sessions.get(user.getId());
        if (oldSession != null
                && !oldSession.equals(session)) {
            //登出老的账号
            SessionManager.INSTANCE.sendMsgTo(session,resp);
        }*/
        session.setUser(user);
        userId2Sessions.put(user.getId(), session);
        session2userIds.put(session, user.getId());
        if (UserType.TEACHER.name().equals(user.getType())) {
            teacherSession.putIfAbsent(user.getId(), session);
        }

        logger.info("[{}] registered...", user.getId());
        return true;
    }

    /**
     * 注销用户通信渠道
     */
    public void ungisterUserDTOContext(Channel context, SessionCloseReason reason) {
        if (context == null) {
            return;
        }
        IoSession session = ChannelUtils.getSessionBy(context);
        Long userId = session2userIds.remove(session);
        userId2Sessions.remove(userId);
        if (teacherSession.containsKey(userId)) {
            teacherSession.remove(userId);
        }
        if (session != null) {
            //session.close(reason);
        }
    }

}
